package com.cxb.demotest.interceptor;

import com.cxb.demotest.annotations.AccessLimit;
import com.cxb.demotest.constant.ResponseConstants;
import com.cxb.demotest.util.RedisUtil;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author Xbao
 * @version 1.0
 * @description 防刷拦截器
 * @date 2021/3/9 11:04
 */
@Component
public class AntiBrushInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  private RedisUtil redisUtil;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    //判断请求是否属于方法的请求
    if(handler instanceof HandlerMethod){

      HandlerMethod hm = (HandlerMethod) handler;
      //获取方法中的注解,看是否有该注解
      AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
      if(accessLimit == null){
        return true;
      }
      int seconds = accessLimit.seconds();
      int maxCount = accessLimit.maxTimes();
      boolean needLogin = accessLimit.needLogin();
      String userId = request.getRequestURI();

      //如果需要登录
      if(needLogin){
        //获取登录的session进行判断
        //.....
        userId = "user";  //这里假设用户是user,项目中是动态获取的userId
      }

      Integer count = (Integer)redisUtil.get(userId);
      if (count == null){
        //第一次访问
        redisUtil.set(userId,1, seconds);
      } else if(count < maxCount){
        redisUtil.incr(userId,1);
      } else {
        render(response, ResponseConstants.ACCESS_LIMIT_REACHED);
        return false;
      }

    }

    return true;

  }
  private void render(HttpServletResponse response, String msg) throws Exception {
    response.setContentType("application/json;charset=UTF-8");
    OutputStream out = response.getOutputStream();
    out.write(msg.getBytes("UTF-8"));
    out.flush();
    out.close();
  }

}
